package com.xxd.spring.boot.demo.lihonghai.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.xxd.spring.boot.demo.lihonghai.entity.User;
import com.xxd.spring.boot.demo.lihonghai.uti.DateUtil;
import com.xxd.spring.boot.demo.lihonghai.uti.UserManageUtil;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import javax.xml.crypto.Data;
import java.util.Date;
import java.util.Objects;

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {


    @Override
    public void insertFill(MetaObject metaObject) {
       boolean creatTime =metaObject.hasGetter("createTime");
       if(creatTime){
          Object createTimeValue = metaObject.getValue("createTime");
           if(Objects.isNull(createTimeValue)){
               metaObject.setValue("createTime",  DateUtil.dateFmt(new Date()));
           }
       }
       boolean createBy = metaObject.hasGetter("createBy");
       if(createBy){
           Object createByValue = metaObject.getValue("createBy");
           if(Objects.isNull(createByValue)){
           User user = UserManageUtil.get();
           metaObject.setValue("createBy", user.getUsername());
       }
    }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        boolean updateTime =metaObject.hasGetter("updateTime");
        if(updateTime){
            Object updateTimeValue = metaObject.getValue("updateTime");
            if(Objects.isNull(updateTimeValue)){
                metaObject.setValue("updateTime",  DateUtil.dateFmt(new Date()));
            }
        }
        boolean updateBy = metaObject.hasGetter("updateBy");
        if(updateBy){
            Object updateByValue = metaObject.getValue("updateBy");
            if(Objects.isNull(updateByValue)){
                User user = UserManageUtil.get();
                metaObject.setValue("updateBy",user.getUsername());
            }
        }
    }
}
